package cn.zebra.dev.city.module.sys.controller;

import cn.zebra.dev.city.module.sys.dto.SysCityDTO;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.sys.module.city.entity.SysCityEntity;
import cn.zebra.dev.sys.module.city.service.SysCityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.ref.SoftReference;
import java.util.*;

/**
 * @author runnable@sina.cn
 */
@Api(tags = "城市服务")
@RestController
public class SysCityController {

    @Autowired
    private SysCityService cityService;

    private SoftReference<Map<Long, Collection<SysCityEntity>>> reference = new SoftReference<>(null);

    @GetMapping("/provincialList")
    @ApiOperation("省级列表")
    public Result<List<SysCityDTO>> provincialList() {
        Map<Long, Collection<SysCityEntity>> map = reference.get();
        if (map == null) {
            map = new HashMap<>(1024);
            map.put(0L, cityService.getProvincialList());
            reference = new SoftReference<>(map);
        }
        Collection<SysCityEntity> list = map.get(0L);
        List<SysCityDTO> data = new LinkedList<>();
        if (list.size() > 0) {
            list.forEach(cityEntity -> {
                SysCityDTO dto = new SysCityDTO();
                BeanUtils.copyProperties(cityEntity, dto);
                data.add(dto);
            });
        }
        return Result.success(data);
    }

    @GetMapping("/itemList/{id}")
    @ApiOperation("下级id")
    public Result<List<SysCityDTO>> itemList(@PathVariable Long id) {
        Map<Long, Collection<SysCityEntity>> map = reference.get();
        if (map == null) {
            map = new HashMap<>(1024);
            reference = new SoftReference<>(map);
        }
        Collection<SysCityEntity> list = map.get(id);
        if (list == null) {
            list = cityService.findListByParentId(id);
            map.put(id, list);
            reference = new SoftReference<>(map);
        }
        List<SysCityDTO> data = new LinkedList<>();
        if (list.size() > 0) {
            list.forEach(cityEntity -> {
                SysCityDTO dto = new SysCityDTO();
                BeanUtils.copyProperties(cityEntity, dto);
                data.add(dto);
            });
        }
        return Result.success(data);
    }
}
